/*
  mkserial.c
*/

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

FILE *in_file;
FILE *out_file;
unsigned int tzero = 0;
unsigned int clockspeed = 0;
unsigned int baudrate = 0;
double tdelta = 0;
double time = 0;


void mkbit(unsigned char b, char *comment) {
  fprintf(out_file, "\t#%i rx = %i; /* %s */\n", (unsigned int)round(tdelta), b, comment);
  //  time += tdelta;
}

int main(int argc, char **argv)
{
  char c;

  if (argc!=6) printf("Usage: %s tzero(ns) clockspeed(MHZ) baudrate(baud) inputfile outputfile\n", argv[0]), exit(1);
  if ((sscanf(argv[1], "%u", &tzero)) != 1) {
    fprintf(stderr, "Bad Time Zero: %s", argv[1]);
    exit(EXIT_FAILURE);
  }

  time = tzero;

  if ((sscanf(argv[2], "%u", &clockspeed)) != 1) {
    fprintf(stderr, "Bad Clock Speed: %s", argv[2]);
    exit(EXIT_FAILURE);
  }
  if ((sscanf(argv[3], "%u", &baudrate)) != 1) {
    fprintf(stderr, "Bad Baud Rate: %s", argv[3]);
    exit(EXIT_FAILURE);
  } 
  if ((in_file = fopen(argv[4], "r")) == NULL) {
    fprintf(stderr, "Error Opening Input File: %s", argv[4]);
    exit(EXIT_FAILURE);
  }
  if ((out_file = fopen(argv[5], "w")) == NULL) {
    fprintf(stderr, "Error Opening Output File: %s", argv[5]);
    exit(EXIT_FAILURE);
  }

  /* No problems with input; do the deed */
  tdelta = ((double) clockspeed*1000000 / (double) baudrate) * (1000 / clockspeed);

  /*
  printf("t0 = %f\n", time);
  printf("clock speed = %i\n", clockspeed);
  printf("baud rate = %i\n", baudrate);
  printf("tdelta=%f\n", tdelta);
  */

  fprintf(out_file, "initial begin: SERIAL /* Generated by mkserial */\n");
  mkbit(1, "RX line starts HIGH");
  while ((c = fgetc(in_file)) != EOF) {
    if (c != '\n') {
      fprintf(out_file, "\t/* Character: '%c' */\n", c);
      mkbit(0, "Start Bit"); /* Start Bit */
      mkbit(c & 1, "Bit 0");
      c >>= 1;
      mkbit(c & 1, "Bit 1");
      c >>= 1;
      mkbit(c & 1, "Bit 2");
      c >>= 1;
      mkbit(c & 1, "Bit 3");
      c >>= 1;
      mkbit(c & 1, "Bit 4");
      c >>= 1;
      mkbit(c & 1, "Bit 5");
      c >>= 1;
      mkbit(c & 1, "Bit 6");
      c >>= 1;
      mkbit(c & 1, "Bit 7");
      mkbit(1, "Stop Bit"); /* Stop Bit */
      mkbit(1, "RX line ends HIGH");
    }
  }

  fprintf(out_file, "end /* Generated by mkserial */\n");
  close(in_file);
  close(out_file);
  return 0;
}
